package com.android.corestat.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年4月18日
 * @version 1.0
 */

public class NetUtils {
	private static final String TAG = "cs-net";

	// // 测试服务器
	// private static final String UPLOAD_URL = "http://192.168.1.200:8888/cdc";
	// //正式环境
	private static final String UPLOAD_URL = "http://cdc.aijiaoyan.com";

	public static HttpURLConnection getCmwapConnect(String requestUrl) throws IOException {
		URL url = new URL(requestUrl);
		HttpURLConnection con;

		CSLog.i(TAG, "use cmwap...");

		String host = url.getHost();
		int port = url.getPort();
		if (port == -1) {
			requestUrl = requestUrl.replaceAll(host, "10.0.0.172:80");
		} else {
			requestUrl = requestUrl.replaceAll(host + ":" + port, "10.0.0.172:80");
		}

		url = new URL(requestUrl);
		con = (HttpURLConnection) url.openConnection();

		String xOnlineHost = null;
		if (port == -1) {
			xOnlineHost = host;
		} else {
			xOnlineHost = host + ":" + port;
		}
		con.setRequestProperty("Host", "10.0.0.172");
		con.setRequestProperty("X-Online-Host", xOnlineHost);
		return con;
	}

	public static void setCommonHttpHeader(HttpURLConnection con) {
		con.setRequestProperty("Accept", "*/*");
		con.setRequestProperty("Accept-Language", "zh-CN, zh");
		con.setRequestProperty("Charset", "UTF-8,ISO-8859-1,US-ASCII,ISO-10646-UCS-2;q=0.6");
		con.setRequestProperty(
				"User-Agent",
				"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
		con.setRequestProperty("Connection", "Keep-Alive");
	}

	public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {
		Map<String, String> header = new LinkedHashMap<String, String>();
		for (int i = 0;; i++) {
			String mine = http.getHeaderField(i);
			if (mine == null)
				break;

			String str = http.getHeaderFieldKey(i);
			if (str != null) {
				header.put(str.toLowerCase(Locale.CHINA), mine);
			}
		}
		return header;
	}

	private static String getChannelNumber(Context c) {
		try {
			ApplicationInfo ai = c.getPackageManager().getApplicationInfo(c.getPackageName(),
					PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			String channelNumber = bundle.getString("CHANNEL");
			return channelNumber;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int uploadLog(Context c, ArrayList<String> logs) {
		if (logs == null || logs.size() == 0) {
			return -1;
		}

		String pkg = Utils.getPackageName(c);
		String channel = null;
		try {
			channel = URLEncoder.encode(getChannelNumber(c), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!TextUtils.isEmpty(channel)) {
			pkg += ":" + channel;
		}

		String urlString = UPLOAD_URL + "/" + pkg;

		String contents = "";
		for (int i = 0; i < logs.size(); ++i) {
			String log = logs.get(i);
			try {
				contents += "content=" + URLEncoder.encode(log, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				return -1;
			}

			if (i < logs.size() - 1) {
				contents += "&";
			}
		}

		HttpURLConnection httpConn = null;
		int retryTimes = 3;

		try {
			while (retryTimes > 0) {
				URL url = new URL(urlString);
				if (Utils.isWap(c)) {
					httpConn = getCmwapConnect(urlString);
				} else {
					httpConn = (HttpURLConnection) url.openConnection();
				}

				httpConn.setDoOutput(true);
				httpConn.setDoInput(true);
				httpConn.setConnectTimeout(60 * 1000);
				httpConn.setReadTimeout(60 * 1000);
				httpConn.setRequestMethod("POST");
				setCommonHttpHeader(httpConn);
				httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");

				boolean gzipOK = false;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				try {
					GZIPOutputStream gzipos = new GZIPOutputStream(baos);
					gzipos.write(contents.getBytes("UTF-8"));
					gzipos.flush();
					gzipos.finish();
					gzipOK = true;
				} catch (Exception e) {
					CSLog.d("NetUtils", "gzip failed:" + ((e == null) ? "" : e.getMessage()));
				}
				if (gzipOK) {
					httpConn.setRequestProperty("Content-Encoding", "gzip");
					httpConn.setRequestProperty("Content-Type", "");
					httpConn.getOutputStream().write(baos.toByteArray());
				} else {
					httpConn.setRequestProperty("Content-Type",
							"application/x-www-form-urlencoded;charset=UTF-8");
					httpConn.getOutputStream().write(contents.getBytes("UTF-8"));
				}

				int statusCode = httpConn.getResponseCode();
				CSLog.d(TAG, "statusCode:" + statusCode);
				if (statusCode != 200) {
					return -2;
				}

				Map<String, String> header = getHttpResponseHeader(httpConn);
				String source = header.get("content-source");
				if (source == null || !source.equals("www.sbx.com")) {
					retryTimes--;
					Thread.sleep(1000);
					continue;
				}

				return 0;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return -4;
		}

		return -3;
	}
}
